#include "terminalglobals.h"
#include <QPixmapCache>

namespace ExecTerminalImplNS 
{

QPixmap pixmapForPath(const QString & path)
{
    QPixmap pm;
    if (!QPixmapCache::find(path, pm)) 
    {
        pm.load(path);
        Q_ASSERT(!pm.isNull());
        QPixmapCache::insert(path, pm);
    }
    return pm;
}

int findNewFirstVisiblePos(int oldFirstVisibleElement,
                           int oldVisibleCount,
                           int newVisibleCount, 
                           int currentElementNumber,
                           int totalCount)
{
    while (oldVisibleCount > newVisibleCount)
    {
        const int visCountFromCurrentToLeft = currentElementNumber - oldFirstVisibleElement;
        const int visCountFromCurrentToRight = newVisibleCount - visCountFromCurrentToLeft - 1;
        const bool leftCountGreater = visCountFromCurrentToLeft > visCountFromCurrentToRight;
        if (leftCountGreater && oldFirstVisibleElement + newVisibleCount < totalCount)
        {
            ++oldFirstVisibleElement;
        }
        oldVisibleCount--;
    }
    while (oldVisibleCount < newVisibleCount)
    {
        const int visCountFromCurrentToLeft = currentElementNumber - oldFirstVisibleElement;
        const int visCountFromCurrentToRight = newVisibleCount - visCountFromCurrentToLeft - 1;
        const bool leftCountSmaller = visCountFromCurrentToLeft < visCountFromCurrentToRight;
        if (leftCountSmaller && oldFirstVisibleElement > 0 || oldFirstVisibleElement + newVisibleCount > totalCount)
        {
            --oldFirstVisibleElement;
            Q_ASSERT(oldFirstVisibleElement >=0 );
        }
        oldVisibleCount++;
    }
    return oldFirstVisibleElement;
}

}//namespace

